package com.itheima.ai.tool;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.ai.dto.CourseQueryDTO;
import com.itheima.ai.po.Course;
import com.itheima.ai.po.CourseReservation;
import com.itheima.ai.po.School;
import com.itheima.ai.service.ICourseReservationService;
import com.itheima.ai.service.ICourseService;
import com.itheima.ai.service.ISchoolService;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 智能客服的Tool工具类
 *
 * @Author mr.wu
 * @Date 2025-11-6 9:19
 */
@Component
public class CourseTool {


    @Autowired
    private ICourseService courseService;


    @Tool(description = "根据条件查询课程")
    public List<Course> queryCourseList(@ToolParam(description = "课程查询条件") CourseQueryDTO courseQueryDTO) {
        //动态根据条件查询课程和排序课程

        //1. 动态拼接查询条件
        QueryWrapper<Course> queryWrapper = Wrappers.<Course>query();

        //动态拼接根据学历查询
        queryWrapper.eq(StrUtil.isNotBlank(courseQueryDTO.getEdu()), "edu", courseQueryDTO.getEdu());

        //动态拼接根据学科类型查询
        queryWrapper.eq(StrUtil.isNotBlank(courseQueryDTO.getType()), "type", courseQueryDTO.getType());

        //2. 动态拼接排序方式
        if(CollUtil.isNotEmpty(courseQueryDTO.getSorts())) {
            //多个排序方式
            List<CourseQueryDTO.Sort> sorts= courseQueryDTO.getSorts();
            //如果排序方式为空就遍历处理，根据指定的排序字段和排序方向来排序
            sorts.forEach(x->{
                String field = x.getField();//排序字段
                Boolean isAsc = x.getIsAsc();//排序方向
                queryWrapper.orderBy(StrUtil.isNotBlank(field) && isAsc!=null, isAsc, field);
            });
        }

        List<Course> courseList = courseService.list(queryWrapper);

        return courseList;
    }

    @Autowired
    private ISchoolService schoolService;

    @Tool(description = "查询全部校区")
    public List<School> queryAllSchool() {
        List<School> schoolList = schoolService.list();
        return schoolList;
    }


    @Autowired
    private ICourseReservationService courseReservationService;

    @Tool(description = "新增试听预约单")
    @Transactional(rollbackFor = Exception.class)
    public Integer createCourseReservation(@ToolParam(description = "课程试听预约信息") CourseReservation courseReservation) {

        courseReservationService.save(courseReservation);
        return courseReservation.getId();
    }

}
